/**
 * <p>Copyright: Copyright (c) 2016</p>
 * <p>Company: gzhc365 </p>
 */
package cn.midi365.train.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.midi365.train.cache.TokenCache;
import cn.midi365.train.common.ErrorCode;
import cn.midi365.train.entity.Secret;
import cn.midi365.train.service.AppService;
import cn.midi365.train.service.SecretService;
import cn.midi365.train.vo.AppDto;

import com.alibaba.fastjson.JSONObject;
import com.eteam.common.entity.TeamContext;
import com.eteam.common.utils.HttpClientUtils;
import com.eteam.common.utils.Utils;
import com.eteam.exceptions.BizException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * Description: TODO {一句话描述类是干什么的}<br/>
 *
 * @author zihong
 * @date: 2018年4月13日 下午10:26:48
 * @version 1.0
 * @since JDK 1.7
 */
@Service
public class AppServiceImpl implements AppService {
    
    Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    private SecretService secretService;
    
    
    @Autowired
    TokenCache tokenCache;

    @Override
    public List<AppDto> getMiniPrograms(TeamContext context) {

        Secret secert = new Secret();
        List<AppDto> miniPrograms = Lists.newArrayList();
        secert.setKeyType("1");
        List<Secret> secrets = secretService.getBy(secert, context);
        if (Utils.isEmpty(secrets)) {
            for (Secret secret : secrets) {
                AppDto miniProgram = new AppDto();
                try {
                    PropertyUtils.copyProperties(miniProgram, secret);
                } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {

                    e.printStackTrace();
                }
                miniPrograms.add(miniProgram);
            }
        }
        return miniPrograms;
    }

    @Override
    public String getAccesToken(String appId, TeamContext context) {
        
        String accessToken = tokenCache.get(appId);
       
        
       if (logger.isDebugEnabled()){
           logger.debug("sequence:{} 缓存中的accessToken数据为:{}",context,accessToken);
       }
        
        if (Utils.isEmpty(accessToken)) {
            Secret  secret=  secretService.getByAppId(appId , "1", context);
            String str = HttpClientUtils.get(context, "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                    + appId + "&secret=" + secret.getSecert(), "utf-8");

           

            JSONObject result = JSONObject.parseObject(str);
            if (Utils.isEmpty(result)) {
                throw new BizException(ErrorCode.RETURNED_VALUE_ERROR, "返回对象为空");
            }

            if (0!=result.getIntValue("errcode")) {
                throw new BizException(ErrorCode.RETURNED_VALUE_ERROR, str);
            }
            accessToken = result.get("access_token").toString();
            tokenCache.set(appId, accessToken);
        }
        return accessToken;
    }

    @Override
    public byte[] getWxAcode(String appId, String path,TeamContext context) {
      String accessToken =  this.getAccesToken(appId,context);
       
       if (Utils.isEmpty(accessToken)) {
           throw new BizException("accessToken为空");
       }
       Map<String,Object> map = Maps.newConcurrentMap();
       map.put("path", path);
       map.put("width", 430);
       return  HttpClientUtils.post(context, "https://api.weixin.qq.com/wxa/getwxacode?access_token="+accessToken, map, "utf-8");
    }

    @Override
    public boolean sendTemplate(String appId, String template,TeamContext context) {
        String accessToken =  this.getAccesToken(appId,context);
        if (Utils.isEmpty(accessToken)) {
            throw new BizException("accessToken为空");
        }
         String  post = HttpClientUtils.post(context, "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken, template, "utf-8");
         Map returnMap = JSONObject.parseObject(post, Map.class);
         return returnMap.get("errcode").equals("0");
    }

}
